<?php
	
	require_once('../includes/config.php');
	require_once('../includes/functions.php');
	
	// Retrieve base HTML
	$pageStr = buildStandardPage('Change Password','Change Password');
	
	/**
	 * Let's generate the content we want to display in this page
	 */
	$content = '';
	
	if(isMobile()){
		$content .= 'Detected Mobile!';
	}
	else{			
		/**
		 * Check if the user already clicked the 'submit' button
		 *   This means they sent their info to the server!
		 */
		if(true == isset($_POST['submit'])){
			$_POST = cleanPost($_POST);
			
			if(true == isset($_POST['answer'])){ // we just came from forgot.php
				$latestAnswer = (hash('sha256', $_POST['answer'] . $_POST['salt']));
				
				if($_POST['answerhash'] == $latestAnswer){ // check if the user submitted the correct answer
					// Allow the user to change their password
					$content .= 'Please enter your email address.<br/><br/>';
					$content .= '<form method=POST action=' . $_SERVER['PHP_SELF'] .  ' onsubmit="return validateChangePasswordForm(this);">';
					$content .= '<input type=hidden value=' . $_POST['id'] . ' name=id >';	
					$content .= '<input type=hidden value=' . $_POST['salt'] . ' name=salt >';	
					
					$content .= '<table><tr><td>Email</td><td>' .$_POST['email']. '</td></tr>';
					$content .= '<tr><td>New Password</td><td><input type=password name=password >';
					$content .= '<tr><td>Confirm Password</td><td><input type=password name=confirmPassword >';
					$content .= '<tr><td></td> <td><input type=submit name=submit value=Login >';
					$content .= '<input type=button value=Cancel onclick="window.location=\'' . $AUTH_URL . '\'" ></td></tr>'
					.'<tr><td></td><td>Not a member? - <a href="'. $USERS_URL .'add.php" >Register Here</a></td></tr></table>';
					$content .= '</form>';
				}
				else{ // The user submitted the wrong answer.
					$content .= 'Sorry the answer you provided was incorrect. '
							. '<br/> Please try to re answer or go to your nearest physical bank.';
				}
			}
			else{ // the user submitted a new password
				$_POST = cleanPost($_POST);
				$newPasswordHash = (hash('sha256', $_POST['password'] . $_POST['salt']));
				
				// change the password!
				$query = buildUpdateStatement('user', array('passwordhash' => $newPasswordHash), $_POST['id']);
				$result = executeSQL($query);
				
				$content .= 'Your password was successfully changed!';
			}
		}
		else{
			header('location:' . $SITE_URL);
		}
	}
	
	/**
	 * Replace the content string
	 */
	$pageStr = str_Replace('<!--content-->', $content, $pageStr);
	
	/**
	 * Send the generated HTML to the client's browser
	 */
	echo $pageStr;
	
	?>